package com.controller;

import com.exception.ValidateException;
import com.pojo.Car;
import io.swagger.annotations.*;
import org.hibernate.validator.constraints.Length;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"汽车校验"},description = "汽车校验")
public class CarCtontroller {

    private static List<Car> list=new ArrayList<>();

    @ApiOperation(value = "汽车新增get请求")
    @GetMapping(value = "car")
    public ResponseEntity<Map<String,Object>> getInsertCar(@Valid Car car, BindingResult result){
        if (result.hasErrors()){
            throw new ValidateException(result.getFieldErrors());
        }

        car.setId(list.size()==0?0:list.get(list.size() - 1).getId()+1);
        list.add(car);
        Map<String,Object> map=new Hashtable<>();
        map.put("msg","get请求新增成功");
        map.put("data",list);
        return ResponseEntity.ok(map);
    }

    @PostMapping(value = "car")
    @ApiOperation(value = "汽车新增post请求")
    public ResponseEntity<Map<String,Object>> postInsertCar(@RequestBody @Valid Car car, BindingResult result){
        if (result.hasErrors()){
            throw new ValidateException(result.getFieldErrors());
        }
        car.setId(list.size()==0?0:list.get(list.size() - 1).getId()+1);
        list.add(car);
        Map<String,Object> map=new Hashtable<>();
        map.put("msg","get请求新增成功");
        map.put("data",list);
        return ResponseEntity.ok(map);
    }

    @GetMapping(value = "test")
    @ApiImplicitParams(
            value = {
                    @ApiImplicitParam(name = "username",value = "用户名",dataType = "String",paramType = "query"),
                    @ApiImplicitParam(name = "age"   ,value = "用户年龄",dataType = "Integer",paramType = "query"),
                    @ApiImplicitParam(name = "flg",value = "用户必须已经出生了",dataType = "Boolean",paramType = "query")
            }

    )
    @ApiOperation(value = "测试校验")
    public ResponseEntity <String> test(

            @NotBlank(message = "用户名不能为空")
            @Length(min = 2,max = 10,message = "用户名长度最小2，最大10")
            @RequestParam("username") String username,
            @Digits(integer = 1,fraction = 80,message = "用户年龄范围是1-80")
            @RequestParam("age") Integer age,
            @AssertTrue(message = "用户必须已经出生了")
            @RequestParam("flg") Boolean flg,
            BindingResult result

    ){
            if (result.hasErrors()){
                throw new ValidateException(result.getFieldErrors());
            }
            return ResponseEntity.ok(username+age+flg);
    }
}

